import 'dart:convert';
import 'dart:ui';

import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:smart_ai_dart/utils/log_utils.dart';

class TranslateService extends Translations {
  // 通过 locals 给 keys 赋值
  Map<String, Map<String, String>> locals = {};
  @override
  Map<String, Map<String, String>> get keys => locals;
  factory TranslateService() => _instance;
  static final TranslateService _instance = TranslateService._internal();

  TranslateService._internal();
  // 支持的语言列表
  static final locales = [
    enLocale,
    zhLocale,
  ];
  static const enLocale = Locale('en', 'US');
  static const zhLocale = Locale('zh', 'CN');

  static Future<void> init() async {
    await _instance.loadTranslations();
  }

  // 加载翻译文件
  Future<void> loadTranslations() async {
    final translations = <String, Map<String, String>>{};

    // 加载每个支持的语言文件
    for (final locale in locales) {
      final languageCode = '${locale.languageCode}_${locale.countryCode}';
      final jsonString =
          await rootBundle.loadString('assets/i18n/$languageCode.json');
      final Map<String, dynamic> jsonMap = json.decode(jsonString);

      translations[languageCode] =
          jsonMap.map((key, value) => MapEntry(key, value.toString()));
      // locals[languageCode] =
      //     jsonMap.map((key, value) => MapEntry(key, value.toString()));
    }

    locals.addAll(translations);
  }

  static void switchLanguage(Locale locale) {
    Get.updateLocale(locale);
    LogUtils.shared.d('Language switched to: $locale');
  }

  static Locale get fallbackLocale => const Locale('en', 'US');
  static TranslateService get instance => _instance;
  static Locale get currentLocale => Get.locale ?? const Locale('zh', 'CN');
}
